#include <cstdio>
#include <thread>
#include <unistd.h>
#include "vl_shared_memory.h"

using namespace VL;

SharedMemory mem(SharedMemory::generateKey(".vl_build/product/bin/vl_shared_memory", 1), 256);

void mainTask() {
	mem.markNotCreate();
	while(!mem.initSharedMemory()) {
		printf("main task failed: initSharedMemory\n");
	}
	if(!mem.attach()) {
		printf("main task failed: attach\n");
	}
	memcpy(mem.getSharedMemory(), "12345", 6);
	if(!mem.detach()) {
		printf("main task failed: detach\n");
	}
}

void forkTask() {
	if(!mem.initSharedMemory()) {
		printf("child task failed: initSharedMemory\n");
	}
	if(!mem.attach()) {
		printf("child task failed: attach\n");
	}
	std::this_thread::sleep_for(std::chrono::seconds(1));
	printf("child task recv: %s\n", (const char *)mem.getSharedMemory());
	if(!mem.detach()) {
		printf("child task failed: detach\n");
	}
}



int main(int argc, const char ** argv) {
	if(fork() == 0) {
		forkTask();
	} else {
		mainTask();
	}
	return 0;
}
